<template>
    <div id="rich-editor"></div>
</template>

<script lang="ts">
import {Component, Model, Vue, Watch} from 'vue-property-decorator';
import Editor from 'wangeditor';
import {SettingsGetterEnum} from "@/store/enum/store.enum";
import enUS from './i18n/en-US';
import zhTW from './i18n/zh-TW';
import {I18nEnum} from "@/common/enum/common.enum";
import i18next from 'i18next';
import xss from 'xss';

/**
 * 富文本编辑器封装
 */
@Component({components: {}})
export default class RichEditor extends Vue {
    /**
     * 传入数据
     */
    @Model('change', {type: String, default: ''})
    public data;
    /**
     * 编辑器实例
     */
    private editor: Editor = null;
    
    private filterXSS: FilterXSS = new xss.FilterXSS({css: false});
    
    /**
     * 初始化
     */
    mounted() {
        if (this.editor === null) {
            this.editor = new Editor(`#rich-editor`);
            // 删除某些不需要的菜单
            const language = this.$store.getters[SettingsGetterEnum.language];
            this.editor.config.lang = language;
            if (language === I18nEnum.enUS) {
                this.editor.config.languages[I18nEnum.enUS] = enUS;
            } else if (language === I18nEnum.zhTW) {
                this.editor.config.languages[I18nEnum.zhTW] = zhTW;
            }
            this.editor.config.excludeMenus = [
                // 表情
                'emoticon',
                // 视频
                'video',
                // 代码
                'code',
                // 图片
                'image'
            ];
            this.editor.i18next = i18next;
            // 配置 onchange 回调函数，将数据同步到 vue 中
            this.editor.config.onchange = (newHtml: string) => {
                this.$emit('change', this.filterXSS.process(newHtml));
            }
            // 创建编辑器
            this.editor.create();
        }
        
        this.editor.txt.html(this.data);
    };
    
    /**
     * 监听数据变化重新将值给富文本编辑器
     * @private
     */
    @Watch('data', {immediate: true})
    private handleData() {
        this.$nextTick(() => {
            this.editor.txt.html(this.filterXSS.process(this.data));
        })
    }
}
</script>
<style lang="scss" scoped>

</style>
    

